package com.orifine.dao;

import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;

public class ResultModel {
	private Map<String, Integer> keyMap;
	private String[] keys;
	private Object[][] values;

	public ResultModel(ResultSet resultSet) throws SQLException {
		keyMap = new HashMap<String, Integer>();
		keys = new String[resultSet.getMetaData().getColumnCount()];
		for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
			keyMap.put(resultSet.getMetaData().getColumnLabel(i+1), i+1);
			keys[i] = resultSet.getMetaData().getColumnLabel(i+1);
		}

		
		resultSet.last();
		values = new String[resultSet.getRow()][keys.length];
		resultSet.first();
		resultSet.previous();
		for (int i = 0; resultSet.next(); i++) {
			for(int j=0; j < keys.length; j++){
				values[i][j] = resultSet.getObject(j+1);
			}
		}
	}

	public <T> T get(Class<T> type) {
		return get(type, 0);
	}
	
	public <T> T get(Class<T> type, int row){
		try {
			return get(type.newInstance(), row);
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public <T> T get(T obj){
		return get(obj, 0);
	}
	
	public <T> T get(T obj, int row){
		//设置obj值实现
		for(int i=0;i < keys.length; i++){
			try {
				PropertyUtils.setProperty(obj, keys[i], values[row][i]);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (ArrayIndexOutOfBoundsException e){
				return null;
			}
		}
		
		return obj;
	}
	
	public <T> List<T> getList(Class<T> type){
		List<T> list = new ArrayList<T>();
		for(int i=0;i < values.length; i++){
			list.add(get(type, i));
		}
		return list;
	}
	
	public List<Map<String, Object>> getListMap(){
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for(int i=0;i < values.length; i++){
			list.add(getMap(i));
		}
		return list;
	}
	
	public Map<String, Object> getMap(){
		return getMap(0);
	}
	
	public Map<String, Object> getMap(int row){
		Map<String, Object> map = new HashMap<String, Object>();
		for(int i =0; i < keys.length; i++){
			map.put(keys[i], values[row][i]);
		}
		return map;
	}
	
	public int getRow(){
		return values.length;
	}
}
